package com.k.jdbc.resultsetmapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ResultSetUtil {

    // Convert ResultSet to a list of objects
    public static <T> List<T> mapResultSetToObjectList(ResultSet resultSet, ResultSetMapper<T> mapper) {
        List<T> resultList = new ArrayList<>();
        try {
            while (resultSet.next()) {
                T object = mapper.mapResultSetToObject(resultSet);
                resultList.add(object);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultList;
    }

    // Close ResultSet
    public static void closeResultSet(ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // Define a functional interface for mapping ResultSet to an object
    public interface ResultSetMapper<T> {
        T mapResultSetToObject(ResultSet resultSet) throws SQLException;
    }

    public static void main(String[] args) {
        ResultSet resultSet = null;
        try {
            // Assume 'resultSet' is obtained from a database query
            List<Person> personList = ResultSetUtil.mapResultSetToObjectList(resultSet, rs -> {
                Person person = new Person();
                person.setId(rs.getInt("id"));
                person.setName(rs.getString("name"));
                person.setAge(rs.getInt("age"));
                return person;
            });
            // Process the list of persons
            for (Person person : personList) {
                System.out.println(person.getId() + ", " + person.getName() + ", " + person.getAge());
            }
        } finally {
            ResultSetUtil.closeResultSet(resultSet);
        }
    }
}
